﻿'------------------------------------------'
'Desevolvido por Jairo dos Santos, Jan/2011'
'------------------------------------------'

Imports System.Data.SqlClient
Imports System.IO

Public Class Principal

    Private dir As String 'Diretório selecionado pelo usuário para efetuar o backup

    Sub New(ByVal modo As String)

        ' This call is required by the Windows Form Designer.
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call.

        If (modo = "restaurar") Then
            gbSalvar.Visible = False
            gbRestaurar.Location = gbSalvar.Location
            Me.Height -= 120
        End If

        Dim frmSplash As New Splash(3)
        frmSplash.ShowDialog()

    End Sub

    Private Sub btnDiagSalvar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDiagSalvar.Click

        Dim dr As DialogResult = folderBrowser.ShowDialog()

        If (dr = Windows.Forms.DialogResult.OK) Then
            If Not (folderBrowser.SelectedPath.Chars(folderBrowser.SelectedPath.Length - 1) = "\") Then
                dir = folderBrowser.SelectedPath + "\"
            Else
                dir = folderBrowser.SelectedPath
            End If

            txtSalvar.Text = dir
            btnSalvar.Enabled = True
        ElseIf (dr = Windows.Forms.DialogResult.Cancel) Then
            txtSalvar.Text = Nothing
            btnSalvar.Enabled = False
        End If
    End Sub

    Private Sub btnDiagRestaurar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDiagRestaurar.Click

        Dim dr As DialogResult = openDialog.ShowDialog()

        If (dr = Windows.Forms.DialogResult.OK) Then
            txtRestaurar.Text = openDialog.FileName
            btnRestaurar.Enabled = True
        ElseIf (dr = Windows.Forms.DialogResult.OK) Then
            txtRestaurar.Text = Nothing
            btnRestaurar.Enabled = False
        End If

    End Sub

    Private Sub openDialog_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles openDialog.FileOk
        txtRestaurar.Text = openDialog.FileName
    End Sub

    Private Sub btnSalvar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSalvar.Click
        If (dir IsNot Nothing) Then
            Select Case (Settings.dataBaseType.ToLower())
                Case "access"
                    Try
                        FileCopy(Settings.dataBaseDir, dir & Path.GetFileNameWithoutExtension(Settings.dataBaseDir) & ".WSB")
                    Catch ex As System.IO.IOException
                        Debug.WriteLine("Erro: " & ex.Message)
                    End Try

                Case "sql"
                    'Se o banco de dados for SQL, dataBaseDir será a String de conexão com o banco
                    Try
                        Dim conn As New SqlConnection(Settings.dataBaseDir)
                        Dim winDrive As String = (Environment.GetEnvironmentVariable("windir", EnvironmentVariableTarget.Machine)).Split("\")(0) + "\"
                        Dim filePath As String = winDrive & conn.Database & ".WSB"
                        Dim query As String = String.Format("BACKUP DATABASE {0} TO DISK = '{1}'", conn.Database, filePath)
                        Dim cmd As New SqlCommand(query, conn)
                        conn.Open()
                        cmd.ExecuteNonQuery()
                        conn.Close()

                        'Substring não funciona. (?)
                        'Ao inves de Substring utilizamos a funcao Mid
                        Rename(filePath, dir + Mid(filePath, filePath.LastIndexOf("\") + 1, filePath.Length - 1))

                    Catch ex As SqlException
                        Debug.WriteLine("Erro: " & ex.Message)
                    Catch ex As IOException
                        Debug.WriteLine("Erro: " & ex.Message)
                    End Try

                Case Else
                    Exit Sub
            End Select

            MessageBox.Show("Backup efetuado com sucesso!", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information)
            txtSalvar.Text = Nothing
            btnSalvar.Enabled = False

        End If
    End Sub

    Private Sub btnRestaurar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRestaurar.Click

        'Previne a tentativa de restaurar sem selecionar um arquivo
        If (New IO.FileInfo(openDialog.FileName).Exists) Then
            Select Case (Settings.dataBaseType.ToLower())

                Case "access"
                    Try
                        FileCopy(openDialog.FileName, Settings.dirToRestore & openDialog.SafeFileName)

                        'Verifica se ja existe um banco de dados
                        Dim fi As New FileInfo(Settings.dirToRestore & Settings.dbName)
                        If (fi.Exists) Then
                            'Se existir, exclui e renomeia o arquivo de backup, tornando o backup utilizavel
                            fi.Delete()
                        End If

                        'Renomeia o arquivo .WSB para .ACCDB
                        Rename(Settings.dirToRestore & openDialog.SafeFileName, Settings.dirToRestore & Settings.dbName)
                    Catch ex As IOException
                        Debug.WriteLine("Erro: " & ex.Message)
                    End Try

                Case "sql"
                    Try
                        'Algumas ações abaixo previnem que a restauracao seja feita com um arquivo da área de trabalho
                        'O SQL Server não importa nem exporta backups da área de trabalho. (?)

                        'Pega o drive de instalação do Windows
                        Dim winDrive As String = (Environment.GetEnvironmentVariable("windir", EnvironmentVariableTarget.Machine)).Split("\")(0) + "\"

                        'Instancia uma nova conexão
                        Dim conn As New SqlConnection(Settings.dataBaseDir)

                        'Pega o novo diretório do arquivo de backup (no caso, a raiz do drive principal)
                        Dim renamedFile As String = winDrive + openDialog.SafeFileName

                        'Copia o arquivo para o novo diretório
                        FileCopy(openDialog.FileName, renamedFile)

                        'Esta parte faz a restauracao
                        '{0} -> O nome do banco
                        '{1} -> Quebra de linha
                        '{2} -> Diretório do arquivo de backup
                        Dim query As String = String.Format("USE MASTER {1} ALTER DATABASE {0} SET SINGLE_USER WITH ROLLBACK IMMEDIATE {1} RESTORE DATABASE {0} FROM DISK = '{2}' {1} ALTER DATABASE {0} SET MULTI_USER", conn.Database, vbNewLine, renamedFile)
                        Dim cmd As New SqlCommand(query, conn)
                        conn.Open()
                        cmd.ExecuteNonQuery()
                        conn.Close()
                        'Fim restauracao

                        'Depois de restaurar, pode excluir o arquivo que está na raiz do drive principal
                        Dim fi As New IO.FileInfo(renamedFile)
                        fi.Delete()

                    Catch ex As SqlException
                        Debug.WriteLine("Erro: " & ex.Message)
                    Catch ex As IO.IOException
                        Debug.WriteLine("Erro: " & ex.Message)
                    End Try

                Case Else
                    Exit Sub

            End Select

            MessageBox.Show("Restauração efetuada com sucesso!", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information)
            txtRestaurar.Text = Nothing
            btnRestaurar.Enabled = False

        End If
    End Sub

End Class
